import store from './store'

function formatNumber(n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function formatPrice(price) {
  return (price / 100).toFixed(2)
}

export function startWith(src, str) {
  const reg = new RegExp('^' + str)
  return reg.test(src)
}

export function endWith(src, str) {
  const reg = new RegExp(str + '$')
  return reg.test(src)
}

export function checkWxLogin() {
  let p = new Promise((resolve, reject) => {
    let userState = {}
    wx.checkSession({
      success: (res) => {
        console.log('res', res)
        if (res.errMsg === 'checkSession:ok') {
          let wxUser = wx.getStorageSync('UserInfo')
          if (wxUser) {
            store.commit('setToken', wxUser.token)
            store.commit('setUser', wxUser)
            userState = {user: wxUser, state: true}
            resolve(userState)
          } else {
            userState = {message: '用户缓存已失效', state: false}
            reject(userState)
          }
        } else {
          userState = {message: '用户缓存已失效', state: false}
          reject(userState)
        }
      },
      fail: (error) => {
        console.error('error', error)
        wx.removeStorageSync('UserInfo')
        userState = {message: '获取用户session已失效', state: false}
        reject(userState)
      },
      complete: (res) => {
        console.log('info', res)
      }
    })
  })
  return p
}

export const host = 'https://mobile-api.microapp.store:8443/'
// export const host = 'https://mobile-api.microapp.store:8443/mobile-api/'
export const fileMgrUrl = host + 'file/getImgStream?idFile='

export const qqMApKey = 'Y5ZBZ-FE36F-CU4J4-NF7QN-UFBM5-4YBDP'

export default {
  formatNumber,
  formatTime,
  formatPrice,
  startWith,
  endWith,
  checkWxLogin,
  host,
  qqMApKey,
  fileMgrUrl
}
